package level4.engines
{
	import flash.display.Stage;
	import flash.events.Event;
	import flash.ui.Keyboard;
	import flash.utils.getTimer;
	
	import level4.input.KeyState;
	import level4.input.Keys;
	import level4.input.MouseState;
	import level4.interfaces.IGameComponent;

	public class GameEngine
	{
		private static var components:Vector.<IGameComponent> = new Vector.<IGameComponent>();
		//持有 舞台的引用
		private static var st:Stage;
		private static var lastTime:Number = 0.0;
		private static var isRun:Boolean;
		
		public function GameEngine(){
			throw new Error("StaticClass ");
		}
		
		/**
		 * 添加
		 * */
		public static function addComponent(component:IGameComponent):void{
			if(!isExist(component)){
				components.push(component);
			}
		}
		/**
		 * 删除 
		 * */
		public static function removeComponent(component:IGameComponent):void{
			if(isExist(component)){
				components.splice(components.indexOf(component),1);
			}
		}
		/**
		 * 检测 是否已经存在
		 * */
		public static function isExist(component:IGameComponent):Boolean{
			var index:int = components.indexOf(component);
			return index > -1;
		}
		/**
		 * 开始主循环
		 * 同时 启动,键盘,鼠标监听.
		 * 
		 * */
		public static function startGame(st:Stage):void{
			if(!isRun){
				GameEngine.st = st;
				st.addEventListener(Event.ENTER_FRAME,gameLoop);
				KeyState.startKeysListening(st);
				MouseState.startMouseListening(st);
				isRun = true;
			}
		}
		/**
		 * 结束主循环
		 * 同时 停止,键盘,鼠标监听.
		 * 
		 * */
		public static function stopGame():void{
			if(st)
				st.removeEventListener(Event.ENTER_FRAME,gameLoop);
			components.length = 0;
			KeyState.stopKeysListening();
			MouseState.stopMouseListening();
			st = null;
			isRun = false;
		}
		/**
		 * 更新 组件状态
		 * */
		private static function gameLoop(e:Event):void{
//			var timeDiff:Number = getTimer() - lastTime;
//			lastTime += timeDiff;
			
			var newTime:Number = getTimer();
			var timeDiff:Number = newTime - lastTime;
				lastTime = newTime;
				Time.deltaTime = timeDiff;
				
			for each(var item:IGameComponent in components){
				item.update(timeDiff);
			}
		}
		//只读 的组件集合
		public static function get Components():Vector.<IGameComponent>{
			return components;
		}
	}
}